package com.lswms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lswms.common.exception.ErrorCode;
import com.lswms.common.exception.RenException;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.MoneyUtil;
import com.lswms.common.utils.RandomDoubleBall;
import com.lswms.common.utils.ZqDateUtil;
import com.lswms.dao.YnLotteryTicketActivityDao;
import com.lswms.dto.YnLotteryTicketActivityDTO;
import com.lswms.dto.vo.req.RandomNumlReq;
import com.lswms.dto.vo.req.SaveNumReq;
import com.lswms.dto.vo.resp.ForecastLuckResp;
import com.lswms.dto.vo.resp.IndexNewRewardResp;
import com.lswms.dto.vo.resp.RandomNumResp;
import com.lswms.dto.vo.resp.TicketResp;
import com.lswms.entity.YnLotteryEntity;
import com.lswms.entity.YnLotteryTicketActivityEntity;
import com.lswms.entity.YnUserEntity;
import com.lswms.service.SysConfigService;
import com.lswms.service.YnLotteryTicketActivityService;
import com.lswms.service.YnUserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import lombok.extern.slf4j.Slf4j;

/**
 * 彩票活动表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-06-20
 */
@Service
@Slf4j
public class YnLotteryTicketActivityServiceImpl extends CrudServiceImpl<YnLotteryTicketActivityDao, YnLotteryTicketActivityEntity, YnLotteryTicketActivityDTO> implements YnLotteryTicketActivityService {

	@Autowired
	private SysConfigService sysConfigService;
	
	@Autowired
	private YnUserService ynUserService;

	
	//新手福利活动code
	private static final String new_reward_code = "IndexNewReward";
	
    @Override
    public QueryWrapper<YnLotteryTicketActivityEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<YnLotteryTicketActivityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    /**
     * 查询是否弹框
     */
	@Override
	public IndexNewRewardResp queryIndexNewReward(YnUserEntity ynuser) {
		log.info("查询是否弹框，参数：{}",JSON.toJSONString(ynuser));
		//返回
		IndexNewRewardResp resp = new IndexNewRewardResp();
		//查询是否弹框
		QueryWrapper<YnLotteryTicketActivityEntity> wrapper = new QueryWrapper<YnLotteryTicketActivityEntity>();
		wrapper.eq("activity_code", new_reward_code);
		wrapper.eq("user_id", ynuser.getId());
		YnLotteryTicketActivityEntity ticket = baseDao.selectOne(wrapper);
		if(ticket != null){
			resp.setStatus("0");
		}
		String value = sysConfigService.queryConfig(new_reward_code);
		resp.setAmount(value);
		log.info("查询是否弹框，返回：{}",JSON.toJSONString(resp));
		return resp;
	}

	/**
	 * 领取奖励
	 */
	@Override
	@Transactional
	public void receiveNewReward(YnUserEntity ynuser) {
		log.info("领取奖励，参数：{}",JSON.toJSONString(ynuser));
		//查询是否已经领取过
		IndexNewRewardResp resp = queryIndexNewReward(ynuser);
		if("0".equals(resp.getStatus())){
			throw new RenException(ErrorCode.IS_RECEIVE);
		}
		//添加领取奖励记录
		BigDecimal reward = MoneyUtil.convertBigDecimal(sysConfigService.queryConfig(new_reward_code));
		YnLotteryTicketActivityEntity entity = new YnLotteryTicketActivityEntity();
		entity.setActivityCode(new_reward_code);
		entity.setAmount(reward);
		entity.setUserId(ynuser.getId());
		entity.setTitle("新手奖励");
		entity.setContent("新手奖励");
		entity.setCreateDate(ZqDateUtil.getNow());
		baseDao.insert(entity);
		//更新用户奖励余额
		BigDecimal totalBalance = ynuser.getReward().add(reward);
		YnUserEntity user = new YnUserEntity();
		user.setId(ynuser.getId());
		user.setReward(totalBalance);
		user.setUpdateDate(ZqDateUtil.getNow());
		ynUserService.updateById(user);
	}

	/**
	 * 预测运势
	 */
	@Override
	public ForecastLuckResp forecastLuck(YnUserEntity ynuser) {
		//运势
		String luck = sysConfigService.queryConfig("Luck");
		String luckDesc = sysConfigService.queryConfig("LuckDesc");
		
		String[] luckA = luck.split(",");
		String[] luckDescA = luckDesc.split("#");
		
		ForecastLuckResp resp = new ForecastLuckResp();
		resp.setLuck(luckA[new Random().nextInt(luckA.length)]);
		resp.setDesc(luckDescA[new Random().nextInt(luckA.length)]);
		resp.setLuckNum((new Random().nextInt(5) + 5)+"");
		resp.setMoneyNum((new Random().nextInt(5) + 5)+"");
		resp.setLotteryNum((new Random().nextInt(5) + 5)+"");
		
		String doubleBall = RandomDoubleBall.getYZHM();
		List<TicketResp> ticket = new ArrayList<TicketResp>();
		//随机双色球
		TicketResp ticketResp = new TicketResp();
		ticketResp.setRedBall(doubleBall.split("\\+")[0]);
		ticketResp.setBlueBall(doubleBall.split("\\+")[1]);
		ticketResp.setType("1");
		ticket.add(ticketResp);
		//随机排列五
		Random random=new Random();
		int num= (int)(random.nextDouble()*(99999-10000 + 1))+ 10000;
		String replace = num+"";
		String regex = "(.{1})";
	    replace = replace.replaceAll(regex, "$1 ");
		ticketResp = new TicketResp();
		ticketResp.setRedBall(replace);
		ticketResp.setType("2");
		ticket.add(ticketResp);
		resp.setTicket(ticket);
		log.info("预测运势,返回resp:{}",JSON.toJSONString(resp));
		return resp;
	}

	/**
	 * 随机号码
	 */
	@Override
	public RandomNumResp randomNum(RandomNumlReq req) {
		log.info("随机号码,req:{}",JSON.toJSONString(req));
		String type = req.getType();
		String count = req.getCount();
		
		RandomNumResp resp = new RandomNumResp();
		List<TicketResp> ticket = new ArrayList<TicketResp>();
		//双色球
		if("1".equals(type)){
			for(int i = 0;i<Integer.parseInt(count);i++){
				String doubleBall = RandomDoubleBall.getYZHM();
				//随机双色球
				TicketResp ticketResp = new TicketResp();
				ticketResp.setRedBall(doubleBall.split("\\+")[0]);
				ticketResp.setBlueBall(doubleBall.split("\\+")[1]);
				ticketResp.setType("1");
				ticket.add(ticketResp);
			}
		//排列五
		}else if("2".equals(type)){
			for(int i = 0;i<Integer.parseInt(count);i++){
				//随机排列五
				Random random=new Random();
				int num= (int)(random.nextDouble()*(99999-10000 + 1))+ 10000;
				String replace = num+"";
				String regex = "(.{1})";
			    replace = replace.replaceAll(regex, "$1 ");
			    TicketResp ticketResp = new TicketResp();
				ticketResp.setRedBall(replace);
				ticketResp.setType("2");
				ticket.add(ticketResp);
			}
		}
		resp.setTicket(ticket);
		log.info("随机号码,返回resp:{}",JSON.toJSONString(resp));
		return resp;
	}

}